<?php

namespace App;

use App\Service\Category;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;

class Post extends Model
{
    /**
     * 发布状态 1发布 2草稿
     */
    const PUBLISHED = 1;
    const DRAFT = 2;
    /**
     *是否推荐1已推荐2未推荐
     */
    const RECOMMENDED = 1;
    const UNRECOMMENDED = 2;

    /**
     *是否启用外部链接
     */
    const USE_LINK = 1;
    const UN_USE_LINK = 0;

    /**
     * Http请求
     * @var $request
     */
    private $request;
    //常用参数操作
    /**
     * @param $status
     *
     * @return mixed
     */
    public function getStatusString($status){
        $statusList =  $this->getStatusList();
        return $statusList[$status];
    }

    /**
     * @param $status
     *
     * @return mixed
     */
    public function getRecommendString($value){
        $config =  $this->getRecommendedList();
        return $config[$value];
    }

    /**
     * @return array
     */
    public static function getStatusList(){
        return [
            self::PUBLISHED =>  '发布',
            self::DRAFT =>  '草稿'
        ];
    }

    public static function getUseLinkList(){
        return [
            self::USE_LINK =>  '外部链接',
            self::UN_USE_LINK =>  '系统链接'
        ];
    }

    public static function getRecommendedList(){
        return [
            self::RECOMMENDED   =>  '推荐',
            self::DRAFT =>  '未推荐'
        ];
    }

    public static function getAraeRateList(){
        return [
          '国家','省','市','县区'
        ];
    }

    //读操作

    public function getSomePosts($constrains,$length = 4){

    }

    public function getPostsByCategory($category_slug,$options = ['order'=>'sort','length'=>4]){
        try{

            $category = Category::where('slug',$category_slug)->first()->toArray();

            if($category){

                $son_id = Category::where('pid',$category['id'])->pluck('id');
                if($son_id){
                    $son_id = $son_id->toArray();
                    array_push($son_id,$category['id']);
                    $model = $this->whereIn('category_id',$son_id)->where('status',self::PUBLISHED);
                }else{
                    $model = $this->where('category_id',$category['id'])->where('status',self::PUBLISHED);
                }
            }
            if(isset($options['order'])){
                $orders = explode(',',$options['order']);
                foreach ($orders as $order){
                    switch ($order){
                        case 'sort':
                            $model = $model->orderBy('sort','asc');
                            break;
                        default:
                            $model = $model->orderBy($order,'desc');
                            break;
                    }
                }
            }else{
                $model = $model->orderBy('id','desc');
            }
            if(isset($options['length'])){
                $model = $model->limit((int)$options['length']);
            }else{
                $model = $model->limit(4);
            }
            return $model->with('category')->get()->toArray();
        }catch (\Exception $e){
            return [];
        }
    }

    public function getPost($id){
        return $this->where('id',$id)->with('category')->where('status',self::PUBLISHED)->first();
    }
    public function getPrev($id,$cat_id = ''){
        $this->where('id','<',$id);
        if($cat_id){
            $this->where('category_id',$cat_id);
        }
        return $this->select('max(id),id,post_title')->first();
    }
    public function getNext($id,$cat_id = ''){
        $this->where('id','>',$id);
        if($cat_id){
            $this->where('category_id',$cat_id);
        }
        return $this->select('min(id),id,post_title')->first();
    }

    /**
     * @param Request $request
     *
     * @return $this|\Illuminate\Database\Eloquent\Builder|static
     */
    public function getPageList(Request $request,$order=false){
        $this->request = $request;
        $model=self::with(['Category']);
        //关键字
        if(isset($this->request->searchKey)){
            $model=$model->where('post_title','like', '%'.$this->request->searchKey.'%');
        }
        //栏目
        if(isset($this->request->category_id)&&$this->request->category_id!=''){
            //获得其子节点
            $ids = Category::where('pid',$this->request->category_id)->pluck('id');
            if($ids){
                $ids = $ids->toArray();
                array_push($ids,$this->request->category_id);
                $model = $model->whereIn('category_id',$ids);
            }else{
                $model=$model->where('category_id','=',$this->request->category_id);
            }
        }
        //县区
        if(isset($this->request->area_id)&&$this->request->area_id){
            $model = $model->where('area_id',$this->request->area_id);
        }
        //状态
        if(isset($this->request->status)&&$this->request->status!=''){
            $model=$model->where('status','=',$this->request->status);
        }
        //时间
        if(isset($this->request->searchTime)&&$this->request->searchTime!=''){
            $timeArray=explode('~',$this->request->searchTime);
            $start_time=trim($timeArray[0]);
            $end_time=trim($timeArray[1]);
            $model=$model->whereBetween('created_at',[$start_time,$end_time]);
        }
        if(isset($this->request->is_recommend) && $this->request->is_recommend){
            $model = $model->where('is_recommend',$this->request->is_recommend);
        }
        if($order==true){
            $model = $model->orderBy('sort','ASC')->orderBy('updated_at','DESC');
        }
        $model=$model->paginate($this->request->limit);

        if($model){
            $model=$model->toArray();
        }
        foreach ($model['data'] as $k=>&$v){
            $v['cat_id'] = $v['category_id'];
            $v['category_id'] = $this->getCategoryName($v['category_id']);
            $v['is_recommend_name'] = self::getRecommendedList()[$v['is_recommend']];
            $v['area_name'] = $this->getAreaName($v['area_id']);
        }
        return $model;
    }
    public function getPageListApi($post){
        $this->request = $post;
        $model=self::with(['Category']);

        //栏目
        if(isset($this->request['category_id'])&&$this->request['category_id']!=''){
            //获得其子节点
            $ids = Category::where('pid',$this->request['category_id'])->pluck('id');
            if($ids){
                $ids = $ids->toArray();
                array_push($ids,$this->request['category_id']);
                $model = $model->whereIn('category_id',$ids);
            }else{
                $model=$model->where('category_id','=',$this->request['category_id']);
            }
        }
        //状态
            $model=$model->where('status','=',self::PUBLISHED);
        //时间
        if(isset($this->request['searchTime'])&&$this->request['searchTime']!=''){
            $timeArray=explode('~',$this->request['searchTime']);
            $start_time=trim($timeArray[0]);
            $end_time=trim($timeArray[1]);
            $model=$model->whereBetween('created_at',[$start_time,$end_time]);
        }
            $model = $model->orderBy('sort','ASC')->orderBy('updated_at','DESC');
        $model=$model->paginate($this->request['limit']);

        if($model){
            $model=$model->toArray();
        }
        return $model;
    }

    //写操作
    /**
     * @param array $id
     */
    public function draft($id = []){
        if($id == []){
            $this->where('status',self::PUBLISHED)->update(['status'=>self::DRAFT]);
        }else{
            if(is_array($id)){
                $this->whereIn('id',$id)->where('status',self::PUBLISHED)->update(['status'=>self::DRAFT]);
            }else{
                $this->where('id',$id)->where('status',self::PUBLISHED)->update(['status'=>self::DRAFT]);

            }
        }
    }

    /**
     * @param array $id
     */
    public function published($id = []){
        if($id == []){
            $this->where('status',self::DRAFT)->update(['status'=>self::PUBLISHED]);
        }else{
            if(is_array($id)){
                $this->whereIn('id',$id)->where('status',self::DRAFT)->update(['status'=>self::PUBLISHED,'created_at'=>date('Y-m-d H:i:s',time())]);
            }else{
                $this->where('id',$id)->where('status',self::DRAFT)->update(['status'=>self::PUBLISHED,'created_at'=>date('Y-m-d H:i:s',time())]);

            }
        }
    }

    public function recommended($id = []){
        if($id == []){
            $this->where('is_recommend',self::UNRECOMMENDED)->update(['is_recommend'=>self::RECOMMENDED]);
        }else{
            if(is_array($id)){
                $this->whereIn('id',$id)->where('is_recommend',self::UNRECOMMENDED)->update(['is_recommend'=>self::RECOMMENDED]);
            }else{
                $this->where('id',$id)->where('is_recommend',self::UNRECOMMENDED)->update(['is_recommend'=>self::RECOMMENDED]);

            }
        }
    }

    public function unrecommended($id = []){
        if($id == []){
            $this->where('is_recommend',self::RECOMMENDED)->update(['is_recommend'=>self::UNRECOMMENDED]);
        }else{
            if(is_array($id)){
                $this->whereIn('id',$id)->where('is_recommend',self::RECOMMENDED)->update(['is_recommend'=>self::UNRECOMMENDED]);
            }else{
                $this->where('id',$id)->where('is_recommend',self::RECOMMENDED)->update(['is_recommend'=>self::UNRECOMMENDED]);

            }
        }
    }

    public function sortCol($id = [],$sort = 50){
        $this->timestamps = false;
        if($id == []){
        }else{
            if(is_array($id)){
                $this->whereIn('id',$id)->where('sort','<>',$sort)->update(['sort'=>$sort]);
            }else{
                $this->where('id',$id)->where('sort','<>',$sort)->update(['sort'=>$sort]);

            }
        }
    }

    /**
     * @param array $id
     */
    public function del($id = []){
            if($id == []){

            }else{
                if(is_array($id)){
                    $this->whereIn('id',$id)->delete();
                }else{
                    $this->where('id',$id)->delete();

                }
            }
    }

    /**
     * @param $post
     */
    public function insertOrUpdate($post){
        if(isset($post['id'])){
            $old = self::find($post['id']);
            $old->post_title = $post['post_title'];
            $old->category_id = $post['category_id'];
            $old->source = $post['source']?$post['source']:'';
            $old->digest = $post['digest']?$post['digest']:'';
            $old->thumb = isset($post['thumb'])?$post['thumb']:'';
            $old->content = isset($post['content'])?$post['content']:'';
            $old->tpl = isset($post['tpl'])?$post['tpl']:'';
            $old->status = isset($post['status'])?$post['status']:self::DRAFT;
            $old->use_link = isset($post['use_link'])?$post['use_link']:self::UN_USE_LINK;
            $old->link = $post['link'];
            $old->is_recommend = isset($post['is_recommend'])?$post['is_recommend']:self::UNRECOMMENDED;
            $old->sort = $post['sort']?$post['sort']:50;
            $old->area_id = isset($post['area_id'])?$post['area_id']:0;
            $old->file = isset($post['file1'])?json_encode($post['file1']):json_encode([]);
            $old->save();
        }else{
            $this->post_title = $post['post_title'];
            $this->category_id = $post['category_id'];
            $this->source = $post['source'];
            $this->digest = $post['digest'];
            $this->thumb = isset($post['thumb'])?$post['thumb']:'';
            $this->content = isset($post['content'])?$post['content']:'';
            $this->tpl = isset($post['tpl'])?$post['tpl']:'';
            $this->status = isset($post['status'])?$post['status']:self::DRAFT;
            $this->use_link = isset($post['use_link'])?$post['use_link']:self::UN_USE_LINK;
            $this->link = $post['link'];
            $this->is_recommend = isset($post['is_recommend'])?$post['is_recommend']:self::UNRECOMMENDED;
            $this->sort = $post['sort']?$post['sort']:50;
            $this->area_id = isset($post['area_id'])?$post['area_id']:0;
            $this->file = isset($post['file1'])?json_encode($post['file1']):json_encode([]);
            $this->save();
        }

    }

    public static function getRecommendPost($cat_id,$length=4){
                //获得其子节点
        $ids = Category::where('pid',$cat_id)->pluck('id');
        $model = self::where('status',self::PUBLISHED);
        if($ids){
            $ids = $ids->toArray();
            array_push($ids,$cat_id);
            $model = $model->whereIn('category_id',$ids);
        }else{
            $model=$model->where('category_id','=',$cat_id);
        }
        $res = $model->where('is_recommend',self::RECOMMENDED)->limit($length)->orderBy('sort','ASC')->orderBy('updated_at','DESC')->get();
        if($res){
            return $res->toArray();
        }else{
            return false;
        }
    }
    //数据实体设置
    /**
     * @param $value
     *
     * @return mixed
     */
    public function getCategoryName($value){
        $config= Category::where('id',$value)->first()->toArray();
        if($config){
            return $config['cat_name'];
        }
        else{
            return false;
        }
    }

    /**
     * @param $value
     *
     * @return mixed
     */
    public function getAreaName($value){
        if($value!=0)
            $config= Area::where('id',$value)->first()->toArray();
        else
            $config = false;
        if($config){
            return $config['name'];

        }else{
            return '全部';
        }

    }
    /**
     * @param $value
     *
     * @return mixed
     */
    public function getStatusAttribute($value){
        $config= $this->getStatusList();
        return $config[$value];
    }

    public function getFileAttribute($value)
    {
        if($value)
            return \GuzzleHttp\json_decode($value,true);
        else
            return $value;
    }
//    public function setFileAttribute($value){
//        return \GuzzleHttp\json_encode($value);
//    }
    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function category(){
        return $this->belongsTo('App\Category','category_id');
    }

    public function area(){
        return $this->belongsTo('App\Area','area_id');
    }


}
